﻿using ICSharpCode.AvalonEdit;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using PDFDesign.Command;
using PDFDesign.Model.Const;
using System.Windows;
using PDFDesign.Properties;
using Newtonsoft.Json.Linq;
using PDFDesign.Common;
using PDFDesign.Repository;
using PDFDesign.Model;

namespace PDFDesign.ViewModel
{
    public class CreateStyleViewModel : BaseViewModel
    {
        private readonly TextEditor textEditor;
        private readonly Dictionary<string, List<double>> PDFSizeDic = new Dictionary<string, List<double>>();

        public CreateStyleViewModel(TextEditor textEditor)
        {
            this.textEditor = textEditor;
            JToken.Parse(Resources.PDFSizes).Children().ToList().ForEach(o =>
            {
                var prop = o as JProperty;
                pdfSizes.Add(prop.Name);
                PDFSizeDic.Add(prop.Name, prop.Value.ToObject<List<double>>());
            });
        }

        /// <summary>
        /// 样式实体
        /// </summary>
        public NewStyleViewModel NewStyleViewModel { get; private set; }

        private string templateName;
        /// <summary>
        /// 模板名称
        /// </summary>
        public string TemplateName
        {
            get => templateName;
            set
            {
                templateName = value;
                OnPropertyChanged("TemplateName");
            }
        }

        private string styleName = "基本样式";
        /// <summary>
        /// 样式名称
        /// </summary>
        public string StyleName
        {
            get => styleName;
            set
            {
                styleName = value;
                OnPropertyChanged("StyleName");
            }
        }

        private double width = 595.28;
        /// <summary>
        /// 宽
        /// </summary>
        public double Width
        {
            get => width;
            set
            {
                width = value;
                OnPropertyChanged("Width");
            }
        }

        private double height = 841.89;
        /// <summary>
        /// 高
        /// </summary>
        public double Height
        {
            get => height;
            set
            {
                height = value;
                TableHeight = value < 200 ? value : value - 200;
                OnPropertyChanged("Height");
            }
        }

        private List<string> pdfSizes = new List<string>();
        /// <summary>
        /// 页面大小列表
        /// </summary>
        public List<string> PDFSizes
        {
            get => pdfSizes;
            set
            {
                pdfSizes = value;
                OnPropertyChanged("PDFSizes");
            }
        }

        private string selectedSize = "A4";
        /// <summary>
        /// 选择的页面大小
        /// </summary>
        public string SelectedSize
        {
            get => selectedSize;
            set
            {
                selectedSize = value;
                if (!string.IsNullOrWhiteSpace(selectedSize))
                {
                    var list = PDFSizeDic[value];
                    Width = list[0];
                    Height = list[1];
                }
                OnPropertyChanged("SelectedSize");
            }
        }

        private bool enabledMode = true;
        /// <summary>
        /// 启用大小模式
        /// </summary>
        public bool EnabledMode
        {
            get => enabledMode;
            set
            {
                enabledMode = value;
                if (value)
                {
                    ModeVisibility = Visibility.Visible;
                    SizeVisibility = Visibility.Collapsed;
                }
                else
                {
                    ModeVisibility = Visibility.Collapsed;
                    SizeVisibility = Visibility.Visible;
                }
                OnPropertyChanged("EnabledMode");
            }
        }

        private Visibility modeVisibility;
        public Visibility ModeVisibility
        {
            get => modeVisibility;
            set
            {
                modeVisibility = value;
                OnPropertyChanged("ModeVisibility");
            }
        }

        private Visibility sizeVisibility = Visibility.Collapsed;
        public Visibility SizeVisibility
        {
            get => sizeVisibility;
            set
            {
                sizeVisibility = value;
                OnPropertyChanged("SizeVisibility");
            }
        }

        private bool isPortrait = true;
        /// <summary>
        /// 是否为纵向
        /// </summary>
        public bool IsPortrait
        {
            get => isPortrait;
            set
            {
                isPortrait = value;
                OnPropertyChanged("IsPortrait");
            }
        }

        private int reportCount = 1;
        /// <summary>
        /// 每页报表数量
        /// </summary>
        public int ReportCount
        {
            get => reportCount;
            set
            {
                reportCount = value;
                OnPropertyChanged("ReportCount");
            }
        }

        private float tableLeft = 50;
        /// <summary>
        /// 表格左边距
        /// </summary>
        public float TableLeft
        {
            get => tableLeft;
            set
            {
                tableLeft = value;
                OnPropertyChanged("TableLeft");
            }
        }

        private float tableTop = 80;
        /// <summary>
        /// 表格上边距
        /// </summary>
        public float TableTop
        {
            get => tableTop;
            set
            {
                tableTop = value;
                OnPropertyChanged("TableTop");
            }
        }

        private bool isFixedRowCount;
        /// <summary>
        /// 是否固定行数
        /// </summary>
        public bool IsFixedRowCount
        {
            get => isFixedRowCount;
            set
            {
                isFixedRowCount = value;
                OnPropertyChanged("IsFixedRowCount");
            }
        }

        private int fixedRowCount;
        /// <summary>
        /// 固定行数
        /// </summary>
        public int FixedRowCount
        {
            get => fixedRowCount;
            set
            {
                fixedRowCount = value;
                OnPropertyChanged("FixedRowCount");
            }
        }

        private double tableHeight;
        /// <summary>
        /// 表格高度
        /// </summary>
        public double TableHeight
        {
            get => tableHeight;
            set
            {
                tableHeight = value;
                OnPropertyChanged("TableHeight");
            }
        }

        private bool? dialogResult;
        /// <summary>
        /// 窗口结果
        /// </summary>
        public bool? DialogResult
        {
            get => dialogResult;
            set
            {
                dialogResult = value;
                OnPropertyChanged("DialogResult");
            }
        }

        /// <summary>
        /// 创建样式
        /// </summary>
        public ICommand CreateStyleCommand => new AnotherCommand(_ =>
        {
            var dataJson = Utils.Format(textEditor.Text, false, out bool success);
            if (!success)
            {
                ShowMessage("数据格式错误");
                return;
            }
            if (string.IsNullOrWhiteSpace(TemplateName))
            {
                ShowMessage("请输入正确的模板名");
                return;
            }
            if (string.IsNullOrWhiteSpace(StyleName))
            {
                ShowMessage("请输入正确的样式名");
                return;
            }
            if (!EnabledMode && (Width <= 0 || Height <= 0))
            {
                ShowMessage("样式大小宽高应大于0");
                return;
            }
            if (ReportCount < 1)
            {
                ShowMessage("每页报表数量至少为1");
                return;
            }
            if (TableLeft < 0)
            {
                ShowMessage("请输入正确的表格左边距");
                return;
            }
            if (TableTop < 0)
            {
                ShowMessage("请输入正确的表格上边距");
                return;
            }
            if (IsFixedRowCount && FixedRowCount < 0)
            {
                ShowMessage("请输入正确得行数");
                return;
            }
            if (ReportStyleRepository.GetInstance().IsExistReportStyle(TemplateName, StyleName))
            {
                ShowMessage($"{TemplateName}的样式[{StyleName}]已存在");
                return;
            }
            try
            {
                var data = Utils.Convert(dataJson);
                if (data == null)
                {
                    throw new Exception("数据转换出错");
                }
                var newStyle = CreateStyleByData(data);
                var guid = Guid.NewGuid().ToString();
                var date = DateTime.Now;
                var resportStyle = new ReportStyles
                {
                    TemplateName = templateName,
                    StyleName = styleName,
                    Content = Newtonsoft.Json.JsonConvert.SerializeObject(newStyle),
                    ConfigId = 0,
                    CustomerId = 7961828763877337388,
                    FileKey = guid,
                    Stylefomattype = 1,
                    StyleNumber = date.ToString("yyyyMMddHHmmss"),
                    Styletype = 1,
                    Id = guid.Replace("-", ""),
                    ProductType = 0,
                    UpdateTime = date,
                    Uploaded = 1,
                    Visitor = ""
                };
                var res = ReportStyleRepository.GetInstance();
                var result = res.Insert(resportStyle);
                if (result == null)
                {
                    throw new Exception("保存数据库异常");
                }
                NewStyleViewModel = new NewStyleViewModel
                {
                    PDFStyle = newStyle,
                    ReportStyle = resportStyle
                };
                DesignUtils.AddSaveData(templateName, dataJson);
                DialogResult = true;
            }
            catch (Exception ex)
            {
                ShowMessage($"样式创建失败:{ex.Message}");
            }
        });

        private NewStyle CreateStyleByData(ReportData data)
        {
            var pageSetting = new PageSetting
            {
                ReportCount = ReportCount,
                Layout = IsPortrait ? Layout.portrait : Layout.landscape,
                Size = new double[] { Width, Height },
                Margins = new Margins { Bottom = 0, Left = 0, Right = 0, Top = 0 }
            };
            var textStyle = new Textstyle
            {
                Font = new Font { Name = FontName.normal, Size = 12 },
                Align = Align.left,
                VAlign = VAlign.top,
                Margins = new Margins { Bottom = 0, Left = 0, Right = 0, Top = 0 }
            };
            var controls = data.MasterFields.Select(field => new Control
            {
                Name = field.Name,
                Caption = field.Name,
                Origin = DataOrigin.master,
                IsPageNumber = false,
                DataField = field.DataField,
                Position = new Position { Top = 20, Left = 50 },
                Size = new Model.Size { Width = 100, Height = 30 },
                ShowCaption = true,
                Type = ControlType.text,
                Value = field.Value,
                RelativeTable = field.IsFooter,
                TextStyle = textStyle
            }).ToList();
            var columns = data.DetailFields.Select(field => new Column
            {
                Name = field.Name,
                FixedWidth = false,
                Precent = 10
            }).ToList();
            var rows = new List<Row>();
            var headerCells = data.DetailFields.Select(field => new Cell
            {
                ColumnSpan = 0,
                TextStyle = textStyle,
                Name = field.Name,
                Origin = DataOrigin.value,
                Value = field.Name
            }).ToList();
            var headerRow = new Row { Type = RowType.header, Height = 30, MultHeader = false, FixedRowHeight = true, Cells = headerCells };
            rows.Add(headerRow);
            var detailCells = data.DetailFields.Select(field => new Cell
            {
                ColumnSpan = 0,
                TextStyle = textStyle,
                Name = field.Name,
                Origin = DataOrigin.detail,
                DataField = field.DataField,
                Value = field.Name
            }).ToList();
            var detailRow = new Row { Type = RowType.detail, Height = 30, MultHeader = false, FixedRowHeight = true, Cells = detailCells };
            rows.Add(detailRow);
            var table = new Table
            {
                Columns = columns,
                Size = new Model.Size
                {
                    Width = width - 100,
                    Height = height - 100
                },
                FixedRowCount = false,
                FixedRows = new List<Row>(),
                Position = new Position { Left = 50, Top = 50 },
                RenderWhiteRow = false,
                RowCount = 0,
                Rows = rows
            };
            var newStyle = new NewStyle
            {
                PageSetting = pageSetting,
                Controls = controls,
                Table = table
            };
            return newStyle;
        }
    }
}
